package com.imay.live.activity.dynamics;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.base.helper.NetworkHelper;
import com.imay.base.util.NetworkUtil;
import com.imay.live.Constants;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.adapter.LabelAdapter;
import com.imay.live.adapter.LabelFeedsAdapter;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.dynamics.DynamicsParams;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.model.FeedModel;
import com.imay.live.model.LabelFeedModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.AutoAdjustRecylerView;
import com.imay.live.view.LoadView;
import com.imay.live.view.dialog.ShareDialogFragment;
import com.imay.live.view.recyclerview.GridVerticalDividerItemDecoration;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.umeng.socialize.UMShareAPI;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 话题格子布局
 * Created by chan on 2017/4/19.
 */

public class LabelFeedsActivity extends BaseRequestActivity {

    private String labelRelatedRequest;
    private String labelNewestRequest;

    private int sinceId;

    private static String LABEL_KEY = "label_key";

    private Context mContext;
    private ArrayList<FeedModel> hotFeeds;
    private ArrayList<FeedModel> releaseFeeds;
    private String label;

    private View viewHead;
    private RecyclerView mRcvLabelFeeds;
    private TwinklingRefreshLayout mRefreshLayout;

    private LabelAdapter mlabelAdapter;
    private LabelFeedsAdapter mlabelFeedsAdapter;

    // 点击时进入热门还是最新
    private int status;
    private final int HOT = 1;
    private final int RELEASE = 2;

    private final int DEFAULT = -1;
    private final int OPEN = 0;
    private final int REFRESH = 1;
    private final int LOAD = 2;

    private volatile int type = DEFAULT;
    private Random random;

    private IMYTBASObject dynamicsupdate;
    private boolean mIsRefresh;
    private LoadView mLoadView;


    /**
     * 传入话题
     *
     * @param activity
     * @param label
     */
    public static void startActivity(Activity activity, String label) {
        Intent intent = new Intent(activity, LabelFeedsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(LABEL_KEY, label);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_label_feeds;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.label_trl_refresh));
        mContext = this;
        type = OPEN;

        random = new Random();

        Bundle b = getIntent().getExtras();
        label = b.getString(LABEL_KEY);

        hotFeeds = new ArrayList<>();
        releaseFeeds = new ArrayList<>();

        initWidget();
        initDatas();
        initListener();
    }

    private void initDatas() {
        mLoadView.setVisibility(View.VISIBLE);
        mLoadView.startLoading();
        labelRelatedRequest = ProtoRequestHelper.task(ProtoHttpFactory.labelRelated(label)).setTag(this.hashCode()).request(this);
        loadData(0, 0, 20);
    }

    private void initWidget() {
        viewHead = LayoutInflater.from(mContext).inflate(R.layout.view_label_feeds_head, null);
        AutoAdjustRecylerView mRcvLabels = $(R.id.rcv_labels, viewHead);
        mRcvLabelFeeds = $(R.id.rcv_label_feeds);

        setTitle(getString(R.string.str_dynamics_jin_text, label));
        getTitleBar().setRightImageResource(R.mipmap.btn_00share);
        getTitleBar().setRightImageOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShareDialog();
            }
        });

        // 相关话题
        WrapContentLinearLayoutManager labelsLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayout.HORIZONTAL);
        mRcvLabels.setLayoutManager(labelsLayoutManager);
        mRcvLabels.setPxPerMillsec(1.0f);
        mlabelAdapter = new LabelAdapter(mRcvLabels);
        mRcvLabels.setAdapter(mlabelAdapter);

        mRcvLabels.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefresh) {
                    return true;
                }
                return false;
            }
        });

        // 话题动态
        mRcvLabelFeeds.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mlabelFeedsAdapter = new LabelFeedsAdapter(true);
        mRcvLabelFeeds.setAdapter(mlabelFeedsAdapter);

        mRefreshLayout = $(R.id.label_trl_refresh);
        RefreshView headerView = new RefreshView(mContext);
        mRefreshLayout.setHeaderView(headerView);
        mRefreshLayout.setBottomView(new LoadingView(mContext));
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setEnableOverScroll(false);

        mLoadView = $(R.id.lv_label);
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        NetworkHelper.getInstance().addListener(new NetworkHelper.NetworkStateListener() {
            @Override
            public void onNetworkChange(int networkType) {
                if (networkType == NetworkUtil.NO_NETWORK) {
                    hotFeeds.clear();
                    releaseFeeds.clear();
                    mlabelAdapter.setNewData(new ArrayList<String>());
                    mlabelFeedsAdapter.setNewData(new ArrayList<>());
                    mLoadView.setVisibility(View.VISIBLE);
                    mLoadView.netError();
                } else {
                    initDatas();
                }
            }
        });

        // 监听数据改变进行布局刷新 1、评论；2、点赞；3、发表动态
        dynamicsupdate = new IMYTBASObject(false);
        dynamicsupdate.stringCommand = EventHelper.EVENT_DYNAMICS_UPDATE;
        dynamicsupdate.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (!TextUtils.isEmpty(imytbasObject.stringData)) {
                    JSONObject jsonObject = JSON.parseObject(imytbasObject.stringData);
                    int action = jsonObject.getIntValue(Constants.DynamicsUpdate.DYNAMICS_ACTION_KEY);
                    FeedModel feed = JSON.parseObject(imytbasObject.stringData, FeedModel.class);
                    List<Object> objects = mlabelFeedsAdapter.getData();
                    switch (action) {
                        case Constants.DynamicsUpdate.ACTION_LABELS_MODIFY:
                            int position = 0;
                            for (Object object : objects) {
                                if (object instanceof FeedModel) {
                                    FeedModel item = (FeedModel) object;
                                    if (item.getFeedId() == feed.getFeedId()) {
                                        item.setMsg(feed.getMsg());
                                        item.setCountLike(feed.getCountLike());
                                        item.setIsLike(feed.isIsLike());
                                        item.setCountComment(feed.getCountComment());
                                        item.setAtUsers(feed.getAtUsers());
                                        item.setLabels(feed.getLabels());
                                        break;
                                    }
                                }
                                position++;
                            }
                            mlabelFeedsAdapter.notifyItemChanged(position);
                            break;
                        case Constants.DynamicsUpdate.ACTION_DYNAMICS_DEL:
                            int positionDel = 0;
                            for (Object object : objects) {
                                if (object instanceof FeedModel) {
                                    FeedModel item = (FeedModel) object;
                                    if (item.getFeedId() == feed.getFeedId()) {
                                        break;
                                    }
                                }
                                positionDel++;
                            }
                            mlabelFeedsAdapter.remove(positionDel + mlabelFeedsAdapter.getHeaderLayoutCount());
                            break;
                        case Constants.DynamicsUpdate.ACTION_DYNAMICE_CREATE:

                            break;
                    }
                }
            }
        });
        dynamicsupdate.addEventListenWithTBASObject();

        mlabelAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String label = mlabelAdapter.getItem(position);
                LabelFeedsActivity.startActivity(LabelFeedsActivity.this, label);
            }
        });


        mlabelFeedsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (!hotFeeds.isEmpty()) {
                    if (position < hotFeeds.size() + 1) {
                        status = HOT;
                        final int realPosition = position - 1;
                        LabelFeedsDetailActivity.start(LabelFeedsActivity.this, getString(R.string.str_dynamics_jin_text, label), realPosition, hotFeeds);
                    } else {
                        status = RELEASE;
                        final int realPosition = position - hotFeeds.size() - 2;
                        LabelFeedsDetailActivity.start(LabelFeedsActivity.this, getString(R.string.str_dynamics_jin_text, label), realPosition, releaseFeeds);
                    }
                } else {
                    status = RELEASE;
                    final int realPosition = position - 1;
                    LabelFeedsDetailActivity.start(LabelFeedsActivity.this, getString(R.string.str_dynamics_jin_text, label), realPosition, releaseFeeds);
                }
            }
        });


        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                mHandler.obtainMessage(0).sendToTarget();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                mHandler.obtainMessage(1).sendToTarget();
            }
        });

        mRefreshLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefresh) {
                    return true;
                }
                return false;
            }
        });
    }


    /**
     * 弹出分享框
     */
    private void showShareDialog() {
        if (!mlabelFeedsAdapter.getData().isEmpty()) {
            String imageUrl = null;
            Object object = mlabelFeedsAdapter.getData().get(1);
            if (object instanceof FeedModel) {
                FeedModel feed = (FeedModel) object;
                if (feed.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
                    imageUrl = feed.getImgUrl();
                } else if (feed.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
                    imageUrl = UrlHelper.getVideoThumbUrl(feed.getVideoUrl());
                }
            }
            UserInfoModel user = UserInfoCache.getUserInfo();
            final String url = UrlHelper.getShareDynamicsLabelUrl(label, user.getUser().getNick());
            String title;
            switch (random.nextInt(4)) {
                case 0:
                    title = getString(R.string.str_label_share_title_1, user.getUser().getNick(), label);
                    break;
                case 1:
                    title = getString(R.string.str_label_share_title_2, user.getUser().getNick(), label);
                    break;
                case 2:
                    title = getString(R.string.str_label_share_title_3, user.getUser().getNick(), label);
                    break;
                case 3:
                    title = getString(R.string.str_label_share_title_4, user.getUser().getNick(), label);
                    break;
                default:
                    title = getString(R.string.str_label_share_title_1, user.getUser().getNick(), label);
                    break;
            }
            final String des = getString(R.string.str_label_share_des);
            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), ShareDialogFragment.newInstance(ShareDialogFragment.WEB, url, title, des, imageUrl));
        }
    }

    /**
     * 刷新
     */
    private void refresh() {
        mlabelFeedsAdapter.getData().clear();
        mlabelFeedsAdapter.notifyDataSetChanged();

        hotFeeds.clear();
        releaseFeeds.clear();

        labelRelatedRequest = ProtoRequestHelper.task(ProtoHttpFactory.labelRelated(label)).setTag(this.hashCode()).request(this);
        loadData(0, 0, 20);
    }

    /**
     * event 加载数据
     *
     * @param count
     */
    private void postEventDataRefresh(int count) {
        mlabelFeedsAdapter.getData().clear();
        try {
            mlabelFeedsAdapter.notifyDataSetChanged();

            releaseFeeds.clear();
            if (!hotFeeds.isEmpty()) {
                ArrayList<Object> list = new ArrayList<>();
                list.add(0, getString(R.string.str_label_hot_feed));
                list.addAll(hotFeeds);
                mlabelFeedsAdapter.addData(list);
            }

            type = REFRESH;
            labelRelatedRequest = ProtoRequestHelper.task(ProtoHttpFactory.labelRelated(label)).setTag(this.hashCode()).request(this);
            loadData(0, 0, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (!mlabelFeedsAdapter.getData().isEmpty()) {
            Object item = releaseFeeds.get(releaseFeeds.size() - 1);
            if (item instanceof FeedModel) {
                FeedModel bean = (FeedModel) item;
                loadData(bean.getFeedId(), 0, 20);
            }
        }
    }

    public void loadData(int sinceId, int maxId, int count) {
        labelNewestRequest = ProtoRequestHelper.task(ProtoHttpFactory.labelNewest(label, sinceId, maxId, count)).setTag(this.hashCode()).request(this);
    }

    /**
     * 回调Success
     *
     * @param command
     * @param data
     */
    @Override
    public void onRequestSuccess(String command, String data) {
        if (type == REFRESH) {
            mRefreshLayout.finishRefreshing();
        } else if (type == LOAD) {
            mRefreshLayout.finishLoadmore();
        }
        mIsRefresh = false;
        if (command.equals(labelRelatedRequest)) {
            Result<LabelFeedModel> result = JSON.parseObject(data, new TypeReference<Result<LabelFeedModel>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                if (!result.data.getFeeds().isEmpty()) {
                    ArrayList<Object> list = new ArrayList();
                    list.add(0, getString(R.string.str_label_hot_feed));
                    list.addAll(result.data.getFeeds());
                    hotFeeds.addAll(result.data.getFeeds());
                    if (type == OPEN || type == REFRESH) {
                        mlabelFeedsAdapter.addData(0, list);
                    }
                }
                if (result.data != null && result.data.getLabels() != null && !result.data.getLabels().isEmpty()) {
                    result.data.getLabels().add(0, getString(R.string.str_label_rang));
                    mlabelAdapter.setNewData(result.data.getLabels());
                    if (mlabelFeedsAdapter.getHeaderLayoutCount() == 0) {
                        mlabelFeedsAdapter.addHeaderView(viewHead);
                    }
                }
            } else {
                ErrorResult.toastError(this, result.result);
            }
        } else if (command.equals(labelNewestRequest)) {
            mLoadView.stopLoading();
            mLoadView.setVisibility(View.GONE);
            Result<List<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<List<FeedModel>>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                ArrayList<Object> list = new ArrayList();
                if (type == OPEN || type == REFRESH) {
                    list.add(getString(R.string.str_label_new_feed));
                    if (result.data.isEmpty()) {
                        mLoadView.loadError();
                        mLoadView.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        mLoadView.setVisibility(View.GONE);
                    }
                } else {
                    mLoadView.setVisibility(View.GONE);
                }
                list.addAll(result.data);
                releaseFeeds.addAll(result.data);
                mlabelFeedsAdapter.addData(list);
            } else {
                ErrorResult.toastError(this, result.result);
            }
        }
    }

    /**
     * 回调Error
     *
     * @param command
     * @param code
     * @param message
     */
    @Override
    public void onRequestError(String command, int code, String message) {
        if (type == REFRESH) {
            mRefreshLayout.finishRefreshing();
        } else if (type == LOAD) {
            mRefreshLayout.finishLoadmore();
        }
        if (NetworkUtil.hasNetwork(mContext)) {
            String error = ErrorResult.getString(mContext, 1);
            mLoadView.loadError(error);
        } else {
            mLoadView.netError();
        }
        //ErrorResult.toastError(this, code);
    }

    /**
     * 刷新回调
     */
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            mIsRefresh = true;
            if (msg.what == 0) {
                type = REFRESH;
                refresh();
            } else if (msg.what == 1) {
                type = LOAD;
                loadMore();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dynamicsupdate != null) {
            dynamicsupdate.destroy();
        }
        NetworkHelper.getInstance().unregisterConnectivityReceiver();
        mHandler.removeCallbacksAndMessages(null);
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }
}
